package it.antonio.ilpizze.db.index.btree.memory;
import it.antonio.ilpizze.db.index.btree.IntermediateNode;
import it.antonio.ilpizze.db.index.btree.Node;
import it.antonio.ilpizze.func.F;
import it.antonio.ilpizze.func.Reducer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class MemoryIntermediateNode<K extends Comparable<K>, V> implements IntermediateNode<K,V>{

	private K key;
	private int degree;
	
	private List<Node<K,V>> elements = new ArrayList<Node<K,V>>();

	public MemoryIntermediateNode(K key, int degree) {
		this.key = key;
		this.degree = degree;
	}
	
	@Override
	public K key() {
		return key;
	}

	@Override
	public boolean isLeaf() {
		return false;
	}


	@Override
	public boolean isFull() {
		return size() >= degree;
	}

	@Override
	public int size() {
		return elements.size();
	}
	
	@Override
	public Iterator<Node<K,V>> iterator() {
		return elements.iterator();
	}

	@Override
	public String toString() {
		return "Node("+key+"){ " + F.reduce(elements, new StringBuffer(), new Reducer<StringBuffer, Node<K,V>>() {

			@Override
			public StringBuffer reduce(StringBuffer b, Node<K,V> obj) {
				if(obj.isLeaf()){
					b.append(obj.key()+ "_l ");
				} else {
					b.append(obj.key()+ "_n ");
				}
				return b;
			}
		}) +"}";
		
	}

	
	@Override
	public boolean isEmpty() {
		return elements.isEmpty();
	}

	@Override
	public void key(K key) {
		this.key = key;
	}

	

	@Override
	public void add(Node<K, V> node) {
		elements.add(node);
	}
	
	@Override
	public Node<K, V> get(int i) {
		return elements.get(i);
	}

	@Override
	public void replace(int index, Node<K,V> one, Node<K,V> two) {

		elements.set(index, one);
		elements.add(index + 1, two);
	}
	
}

